package com.jstyle.jclife.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;


import com.amap.api.maps.MapsInitializer;
import com.jstyle.jclife.R;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclife.model.BindDeviceInfo;

import com.jstyle.jclife.model.Device1751;
import com.jstyle.jclife.model.Device1755;
import com.jstyle.jclife.model.Device1790;

import com.jstyle.jclife.model.Device1810;
import com.jstyle.jclife.model.Device1860;
import com.jstyle.jclife.model.Device1929;
import com.jstyle.jclife.model.JstyleDevice;
import com.jstyle.jclife.utils.DbManager;
import com.jstyle.jclife.utils.SharedPreferenceUtils;

import com.tencent.bugly.crashreport.CrashReport;

import java.util.List;

import uk.co.chrisjenx.calligraphy.CalligraphyConfig;

/**
 * Created by Administrator on 2018/6/11.
 */

public class MyApplication extends MultiDexApplication implements Application.ActivityLifecycleCallbacks {
    private static final String TAG = "MyApplication";
    public static JstyleDevice jstyleDevice;
    private ListenerReceiver receiver;
    Activity activity;
    private static MyApplication instance;
    @Override
    public void onCreate() {
        super.onCreate();
//        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
//        StrictMode.setVmPolicy(builder.build());
//        builder.detectFileUriExposure();

        Log.i(TAG, "onCreate: " + getPidName());
        if (!TextUtils.isEmpty(getPidName()) && getPidName().equals(getPackageName())) {
            instance=this;
            registerReceiver();
            registerActivityLifecycleCallbacks(this);
            BleManager.init(this);
            DbManager.init(this);
        //    MobSDK.init(this);
            SharedPreferenceUtils.init(this);

//            CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
//                    .setDefaultFontPath("ROBOTO-REGULAR_2.TTF")
//                    .build()
//            );
            CrashReport.initCrashReport(getApplicationContext(), getString(R.string.bugly_id), false);
            String dfuAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_DFU_ADDRESS);
           if (!TextUtils.isEmpty(dfuAddress)) return;
           // boolean isLogin= SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_LOGIN,false);

            String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
            if (!TextUtils.isEmpty(address))
                BleManager.getInstance().connectDevice(address);
        }
    }
    public static MyApplication instance() {
        return MyApplication.instance;
    }

    private String getPidName() {
        int pid = android.os.Process.myPid();
        String processName = "";
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

        List<ActivityManager.RunningAppProcessInfo> list = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : list) {
            if (runningAppProcessInfo.pid == pid) {
                processName = runningAppProcessInfo.processName;
            }
        }
        return processName;

    }

    public static JstyleDevice getJstyleDevice() {
        JstyleDevice jstyleDevice = new Device1755();
        String address=SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        if (TextUtils.isEmpty(address)) return jstyleDevice;
        BindDeviceInfo bindDeviceInfo= BindDeviceInfoDaoManager.queryData(address);
        if(bindDeviceInfo==null)return jstyleDevice;
        String name=bindDeviceInfo.getDeviceName();
        if(TextUtils.isEmpty(name))return jstyleDevice;
        if(name.toLowerCase().contains(JstyleDevice.device_1790)){
            jstyleDevice = new Device1790();
        }else if(name.toLowerCase().contains(JstyleDevice.device_1755)){
            jstyleDevice = new Device1755();
        }else if(name.toLowerCase().contains(JstyleDevice.device_1810)){
            jstyleDevice=new Device1810();
        }else if(name.toLowerCase().contains(JstyleDevice.device_1751)){
            jstyleDevice=new Device1751();
        }else if(name.toLowerCase().contains(JstyleDevice.device_1860)){
            jstyleDevice=new Device1860();
        }else if(name.toLowerCase().contains(JstyleDevice.device_1929)||name.toLowerCase().contains(JstyleDevice.device_healy)){
            jstyleDevice=new Device1929();
        }
        return jstyleDevice;
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();

        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        receiver = new ListenerReceiver();
        registerReceiver(receiver, filter);
    }
    @Override
    public void onTerminate() {
        super.onTerminate();
        Log.i(TAG, "onTerminate: ");
    }
    public static String getAppVersion(Context context) {
        PackageInfo packageInfo;
        String versionName = "";
        try {
            packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;

    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {
        this.activity=activity;
        Log.i(TAG, "onActivityResumed: "+activity.getLocalClassName());
    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }

    class ListenerReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action=intent.getAction();
            if(action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)){
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                        BluetoothAdapter.ERROR);
                switch (state) {
                    case BluetoothAdapter.STATE_ON:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                final String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
                                if(!TextUtils.isEmpty(address)){
                                    BleManager.getInstance().reConnect();
                                }
                            }
                        },600);


                        Log.i(TAG, "onReceive: 开启蓝牙");
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        BleManager.getInstance().disconnectDeviceAndClose();
                        Log.i(TAG, "onReceive: 关闭蓝牙");
                        break;

                }
            }
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public Activity getShowActivity(){
        return this.activity;
    }
    public void showView(View view) {
        /*Activity不为空并且没有被释放掉*/
        if (this.activity != null && !this.activity.isFinishing()) {
            /*获取Activity顶层视图,并添加自定义View*/
            ((ViewGroup) this.activity.getWindow().getDecorView()).addView(view);
        }
    }


    public void hideView(View view) {
        if (this.activity != null && !this.activity.isFinishing()) {
            ViewGroup root = ((ViewGroup) this.activity.getWindow().getDecorView());
            /*如果Activity中存在View对象则删除*/
            if (root.indexOfChild(view) != -1) {
                /*从顶层视图中删除*/
                root.removeView(view);
            }
        }
    }
    private float mNonCompatDensity;
    private float mNonCompatScaledDensity;
    public   void setAppOrientation(@NonNull Activity activity, final Application application) {
        final DisplayMetrics appDisplayMetrics=application.getResources().getDisplayMetrics();
        if(mNonCompatDensity==0){
            mNonCompatDensity=appDisplayMetrics.density;
            mNonCompatScaledDensity=appDisplayMetrics.scaledDensity;
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if(newConfig!=null&&newConfig.fontScale>0){
                        mNonCompatScaledDensity=application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }
        float targetDensity=appDisplayMetrics.widthPixels/401f;
        float targetScaledDensity = targetDensity * (mNonCompatScaledDensity / mNonCompatDensity);
        int targetDensityDpi = (int) (160 * targetDensity);
        appDisplayMetrics.density = targetDensity;
        appDisplayMetrics.scaledDensity = targetScaledDensity;
        appDisplayMetrics.densityDpi = targetDensityDpi;
        // 最后在这里将修改过后的值赋给系统参数,只修改Activity的density值
        DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = targetDensity;
        activityDisplayMetrics.scaledDensity = targetScaledDensity;
        activityDisplayMetrics.densityDpi = targetDensityDpi;

    }
}
